import axios from 'axios'
import { /* MessageBox, */Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: '',
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout

})
// request interceptor
service.interceptors.request.use(
  config => {
    // 加入cancelToken对象，路由切换时清除上一个路由的未响应请求信息
    try {
      config.cancelToken = new axios.CancelToken((calcel) => {
        window.axiosPromiseArr.push({ calcel })
      })
    } catch (error) {
      console.log(error)
    }
    if (config.notLoading !== 1) {
      // do something before request is sent
      store.dispatch('common/setReqNum', 1)
      store.dispatch('common/setReqType', 0)
    }
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken()
    // }
    return config
  },
  error => {
    // store.dispatch('common/setReqNum', 1)
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (response.config.notLoading !== 1) {
      // do something before request is sent
      window.setTimeout(() => {
        store.dispatch('common/setReqNum', -1)
        store.dispatch('common/setReqType', 0)
      }, 1)
    }
    // const res = response.data
    return response
  },
  err => {
    window.setTimeout(() => {
      store.dispatch('common/setReqNum', -1)
      store.dispatch('common/setReqType', 0)
    }, 1)
    if (axios.isCancel(err)) {
      // cancel请求
      return Promise.reject(err)
    }
    console.log('err  ' + err, err.response) // for debug
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误'
          break

        case 401:
          err.message = '未授权，请登录'
          break

        case 403:
          err.message = '拒绝访问'
          break

        case 404:
          err.message = `请求地址出错: ${err.response.config.url}`
          break

        case 408:
          err.message = '请求超时'
          break

        case 500:
          err.message = '服务器内部错误'
          break

        case 501:
          err.message = '服务未实现'
          break

        case 502:
          err.message = '网关错误'
          break

        case 503:
          err.message = '服务不可用'
          break

        case 504:
          err.message = '网关超时'
          break

        case 505:
          err.message = 'HTTP版本不受支持'
          break

        default:
          err.message = '未知错误'
      }
    }
    Message({
      message: err.message,
      type: 'error',
      duration: 5 * 1000
    })
    const { status } = err.response || {}
    if (status === 403 || status === 401) {
      try {
        if (window.$loginUrl) {
          window.$toLoginFunc()
        } else {
          window._VUE_INSTANCE.$router.push('/login')
        }
      } catch (error) {
        console.log(error)
        if (window.$loginUrl) {
          window.$toLoginFunc()
        } else {
          window.location.href = window.location.origin
        }
      }
      return Promise.reject(err)
    }
    return Promise.reject(err)
  }
)
const request = (param) => {
  const _ = new Date().getTime()
  if (param.params) {
    Object.assign(param.params, {
      _: _
    })
  } else {
    Object.assign(param, {
      params: {
        _: _
      }
    })
  }
  if (param.headers) {
    Object.assign(param.headers, {
      'X-Requested-With': 'XMLHttpRequest'
    })
  } else {
    param.headers = {
      'X-Requested-With': 'XMLHttpRequest'
    }
  }

  return new Promise((resolve, reject) => {
    service(param).then((res) => {
      const data = res.data
      if (data.success === true||data.status===1000) {
        resolve(data)
      } else {
        if (param.url === '/web/sysPermission/all') {
          // 过滤掉获取routes的拦截
          resolve(data)
          return
        }
        // do nothing
        Message({
          message: data.message || data.msg || 'Error',
          type: 'warning',
          duration: 5 * 1000
        })
        if (data.status === 403 || data.status === 5001 || data.status === 5002) {
          if (data.status === 403) {
            // ?redirect=${window._VUE_INSTANCE.$route.fullPath}
            if (window.$loginUrl) {
              window.$toLoginFunc()
            } else {
              window._VUE_INSTANCE.$router.push(`/login`)
            }
          }
        }
        reject(data)
      }
    }).catch((err) => { reject(err) })
  })
}
export default request
